import { AppComstants, MenuType } from '@/common/comstants';
import { appLocalStorage } from '@/utils/storage-util';

const modules = import.meta.glob('../views/**/**.vue');

function getComponentByName(componentName) {
  return Object.keys(modules).find((key) => key.endsWith(`${componentName}.vue`))
    ? modules[Object.keys(modules).find((key) => key.endsWith(`${componentName}.vue`))]
    : null;
}

/** 路由转换 */
function transformRoutes(menuList, routes = []) {
  routes.forEach((menu) => {
    const childrens = menuList.filter((item) => item.parentId === menu.meta.menuId);
    for (const childrenMenu of childrens) {
      const component = getComponentByName(childrenMenu.component);
      const router = {
        path: childrenMenu.path,
        name: childrenMenu.name,
        redirect: childrenMenu.redirect,
        component,
        meta: childrenMenu,
        children: [],
        menuId: childrenMenu.menuId,
      };
      menu.children.push(router);
      if (childrenMenu.menuType === MenuType.CATALOG) {
        transformRoutes(menuList, menu.children);
      }
    }
  });
}

function updateRoute(menuList) {
  const menus = [];
  for (const menu of menuList) {
    if (menu.parentId === 0) {
      const component = getComponentByName(menu.component);
      menus.push({
        path: menu.path,
        name: menu.name,
        redirect: menu.redirect,
        component,
        meta: menu,
        children: [],
        menuId: menu.menuId,
      });
    }
  }

  transformRoutes(menuList, menus);

  return menus;
}

function initRoutes(router) {
  if (appLocalStorage.getItem(AppComstants.MENUS)) {
    const menus = appLocalStorage.getItem(AppComstants.MENUS);
    const menuRoutes = updateRoute(menus);

    menuRoutes.forEach((route) => {
      router.addRoute('layout', route);
    });
  }
}

export { updateRoute, initRoutes };
